<!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../bower_components/plugin-element/plugin-element.html">
<link rel="import" href="../bower_components/app-layout/app-header/app-header.html">
<link rel="import" href="../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../bower_components/iron-icon/iron-icon.html">
<link rel="import" href="../bower_components/app-layout/app-scroll-effects/effects/waterfall.html">
<link rel="import" href="../bower_components/app-layout/app-toolbar/app-toolbar.html">
<link rel="import" href="../bower_components/app-layout/helpers/helpers.html">
<link rel="import" href="../bower_components/app-route/app-location.html">
<link rel="import" href="../bower_components/app-route/app-route.html">
<link rel="import" href="../bower_components/app-route/app-route-converter.html">
<link rel="import" href="../bower_components/iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="../bower_components/iron-media-query/iron-media-query.html">
<link rel="import" href="../bower_components/iron-pages/iron-pages.html">
<link rel="import" href="../bower_components/iron-selector/iron-selector.html">
<link rel="import" href="../bower_components/plugin-element/plugin-xhr.html">
<link rel="import" href="../bower_components/plugin-element/plugin-websocket.html">
<link rel="import" href="../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../bower_components/paper-spinner/paper-spinner-lite.html">

<link rel="import" href="shop-category-data.html">
<!-- Since 'home' is the default route, eagerly load it. -->
<link rel="import" href="shop-home.html">
<link rel="import" href="shop-business.html">
<link rel="import" href="shop-activity.html">
<link rel="import" href="shop-school.html">
<link rel="import" href="shop-my.html">
<dom-module id="shop-app">

    <template>

    <style>

      :host {
        display: block;
        position: relative;
        padding-top: 130px;
        padding-bottom: 64px;
        min-height: 100vh;
        --app-primary-color: #202020;
        --app-secondary-color: #757575;
        --app-accent-color: #172C50;
        --paper-button-ink-color: var(--app-accent-color);
        --paper-icon-button-ink-color: var(--app-accent-color);
        --paper-spinner-color: var(--app-accent-color);
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
        color: var(--app-primary-color);
      }

      app-header {
        @apply --layout-fixed-top;
        z-index: 1;
        background-color: rgba(255, 255, 255, 0.95);
        --app-header-shadow: {
          box-shadow: inset 0px 5px 6px -3px rgba(0, 0, 0, 0.2);
          height: 10px;
          bottom: -10px;
        };
          border-bottom: #ddd solid 1px;
      }

      paper-icon-button {
        color: var(--app-primary-color);
      }
        app-toolbar{padding: 0px;}
        app-toolbar paper-listbox{
            display: flex;
            justify-content:space-between;
            height: 100%;
            width: 100%;
            padding: 0px;
            --paper-listbox-background-color:none;
        }
        app-toolbar paper-listbox paper-item{
            font-size: 12px;
            color: var(--app-primary-color);
            text-decoration: none;
            /* required for IE 11, so this <a> can receive pointer events */
            display:flex;
              flex-direction: column;
              align-items: center;
            pointer-events: auto;
            flex: 1;
            justify-content: center;
            align-items: center;
        }
        app-toolbar paper-listbox paper-item.iron-selected[focused]{
            color: #fff;
            background: #fff;
        }
        app-toolbar paper-listbox paper-item.iron-selected>*{
            color: green;
            font-weight: normal;
        }
      .announcer {
        position: fixed;
        height: 0;
        overflow: hidden;
      }

      :host(:not([page=detail])) .back-btn {
        display: none;
      }

      [hidden] {
        display: none !important;
      }

      iron-pages {
        max-width: 1440px;
        margin: 0 auto;
      }

      /* small screen */
      @media (max-width: 767px) {
        :host {
          padding-top: 64px;
        }

        .menu-btn {
          display: block;
        }

        :host([page=detail]) .menu-btn {
          display: none;
        }
      }
      *, :focus, :hover, :active {
            outline:0;
        }
        a:focus{
            -webkit-tap-highlight-color:rgba(0,0,0,0);
            -webkit-user-modify:read-write-plaintext-only;
            outline:0;
        }
        
    </style>
    <plugin-websocket id="websocket" auto url="{{wsHost}}/websocket/p2p?plugin_{{_cookie('token')}}" on-message="_websocketMessage"></plugin-websocket>
    <paper-spinner-lite style="position: fixed;left: 50%;top: 50%;margin-left:-20px;margin-top:-20px;z-index: 99999" id="loading" alt="loading..." class="orange"></paper-spinner-lite>
    <shop-analytics key="UA-39334307-16"></shop-analytics>
    <!--
      app-location and app-route elements provide the state of the URL for the app.
    -->
    <app-location id="appLocation" route="{{route}}"></app-location>
    <app-route
        route="{{route}}"
        pattern="/:page"
        data="{{routeData}}"
        tail="{{subroute}}"></app-route>
    <app-route-converter
        path="{{route.path}}"
        query-params="{{queryParams}}"
        route="{{route}}">
    </app-route-converter>
    <iron-media-query query="max-width: 767px" query-matches="{{smallScreen}}"></iron-media-query>

    <app-header role="navigation" id="header" effects="waterfall" condenses reveals>
      <app-toolbar>
        <paper-listbox selected="0">
            <paper-item href="/" on-click="_page"><iron-icon icon="home"></iron-icon><span>主页</span></paper-item>
            <paper-item href="/business" on-click="_page"><iron-icon icon="track-changes"></iron-icon><span>分销</span></paper-item>
            <paper-item href="/my" on-click="_page"><iron-icon icon="account-balance-wallet"></iron-icon><span>收入</span></paper-item>
            <paper-item href="/activity" on-click="_page"><iron-icon icon="event"></iron-icon><span>活动</span></paper-item>
            <paper-item href="/school" on-click="_page"><iron-icon icon="account-balance"></iron-icon><span>学堂</span></paper-item>
            
        </paper-listbox>
      </app-toolbar>

      <!-- Lazy-create the tabs for larger screen sizes. -->
      <div id="tabContainer" sticky$="[[_shouldShowTabs]]" hidden$="[[!_shouldShowTabs]]">
        <dom-if if="[[_shouldRenderTabs]]">
          <template>
            <shop-tabs
                selected="home"
                attr-for-selected="name">
              <shop-tab name="home">
                  <a href="home">主页</a>
                  <a href="business">商机</a>
                  <a href="activity">活动</a>
                  <a href="school">学堂</a>
                  <a href="my">我的分销</a>
                </shop-tab>
    </shop-tabs>
    </template>
    </dom-if>
    </div>
    </app-header>


    <iron-pages role="main" selected="[[page]]" attr-for-selected="name" selected-attribute="visible" fallback-selection="404">
        <shop-home name="home"></shop-home>
        <shop-business name="business"></shop-business>
        <shop-activity name="activity"></shop-activity>
        <shop-school name="school"></shop-school>
        <shop-my name="my"></shop-my>
    </iron-pages>
    <!-- a11y announcer -->
    <div class="announcer" aria-live="assertive">[[_a11yLabel]]</div>

    </template>

    <script>
        var app;
        // performance logging
        window.performance && performance.mark && performance.mark('shop-app - before register');

        class ShopApp extends PluginElement {

            static get is() {
                return 'shop-app';
            }

            static get properties() {
                return {
                    page: {
                        type: String,
                        reflectToAttribute: true,
                        observer: '_pageChanged'
                    },
                    _shouldShowTabs: {
                        computed: '_computeShouldShowTabs(page, smallScreen)'
                    },

                    _shouldRenderTabs: {
                        computed: '_computeShouldRenderTabs(_shouldShowTabs, loadComplete)'
                    },

                    _shouldRenderDrawer: {
                        computed: '_computeShouldRenderDrawer(smallScreen, loadComplete)'
                    },
                    apiHost: {
                        type: String,
                        value: "https://" + (window.location.hostname.indexOf("template.") == 0 ? "appcenter.b2wx.com" : window.location.hostname) + "/plugin/api"
                    },
                    httpHost: {
                        type: String,
                        value: function() {
                            return "https://" + (window.location.hostname.indexOf("template.") == 0 ? "appcenter.b2wx.com" : window.location.hostname);
                        }
                    },
                    wsHost: {
                        type: String,
                        value: function() {
                            return "wss://" + (window.location.hostname.indexOf("template.") == 0 ? "appcenter.b2wx.com" : window.location.hostname);
                        }
                    },
                    loadingCount: {
                        type: Number,
                        value: 0
                    },
                    pluginNotifyListener: {
                        type: Object,
                        value: {}
                    }
                }
            }

            static get observers() {
                return [
                    '_routePageChanged(routeData.page)'
                ]
            }

            constructor() {
                super();
                app = this;
                this.appId = this._param("app_id");
                window.performance && performance.mark && performance.mark('shop-app.created');
            }

            ready() {
                document.title = "微捷分销平台";
                super.ready();
                // Custom elements polyfill safe way to indicate an element has been upgraded.
                this.removeAttribute('unresolved');
                // listen for custom events
                this.addEventListener('change-section', (e) => this._onChangeSection(e));
                this.addEventListener('announce', (e) => this._onAnnounce(e));
                this.addEventListener('dom-change', (e) => this._domChange(e));
                this.addEventListener('show-invalid-url-warning', (e) => this._onFallbackSelectionTriggered(e));
                // listen for online/offline
                Polymer.RenderStatus.afterNextRender(this, () => {
                    window.addEventListener('online', (e) => this._notifyNetworkStatus(e));
                    window.addEventListener('offline', (e) => this._notifyNetworkStatus(e));
                });
                //this.callApi("showShareMenu",{withShareTicket: true});
                this.pluginNotifyListener.notify = function(config) {
                    if (config.success) {
                        config.success.call(app, {
                            errMsg: "ok"
                        });
                    }
                }
            }
            _websocketMessage(e) {
                let dom = this;
                let data = e.detail;
                if (data == "heartbeat") {
                    return;
                }
                let to = "plugin_" + dom._cookie("token");
                let type = data.type;
                let apiNmae = data.name;
                let config = data.config;
                let callbacks = data.callbacks;
                if (typeof(data) == "object") {
                    if (data.type == "api") {
                        if (app.pluginNotifyListener[data.name]) {
                            if (callbacks) {
                                for (let callback in callbacks) {
                                    let callbackFun = callbacks[callback];
                                    config[callback] = function(res) {
                                        app.$.websocket.send(JSON.stringify({
                                            to: to,
                                            data: {
                                                result: res,
                                                callback: callbackFun
                                            }
                                        }));
                                    }
                                }
                            }
                            app.pluginNotifyListener[data.name].call(app, config);
                        } else {
                            app.$.websocket.send(JSON.stringify({
                                to: to,
                                data: {
                                    result: {
                                        errMsg: "接口不存在"
                                    },
                                    callback: "fail"
                                }
                            }));
                        }
                    }
                }
            }
            _routePageChanged(page) {
                if (this.page === 'list') {
                    this._listScrollTop = window.pageYOffset;
                }
                this.page = page && page != "distribution.pl" ? page : 'home';

                // Close the drawer - in case the *route* change came from a link in the drawer.
                this.drawerOpened = false;
            }

            _pageChanged(page, oldPage) {
                if (page != null) {
                    // home route is eagerly loaded
                    if (page == 'home') {
                        this._pageLoaded(Boolean(oldPage));
                        // other routes are lazy loaded
                    } else {
                        // When a load failed, it triggered a 404 which means we need to
                        // eagerly load the 404 page definition
                        let cb = this._pageLoaded.bind(this, Boolean(oldPage));
                        Polymer.importHref(this.resolveUrl('shop-' + page + '.html'), cb, cb, true);
                    }
                }
            }

            _pageLoaded(shouldResetLayout) {
                this._ensureLazyLoaded();
                if (shouldResetLayout) {
                    // The size of the header depends on the page (e.g. on some pages the tabs
                    // do not appear), so reset the header's layout only when switching pages.
                    Polymer.Async.timeOut.run(() => {
                        this.$.header.resetLayout();
                    }, 1);
                }
            }

            _ensureLazyLoaded() {
                // load lazy resources after render and set `loadComplete` when done.
                if (!this.loadComplete) {
                    Polymer.RenderStatus.afterNextRender(this, () => {
                        Polymer.importHref(this.resolveUrl('lazy-resources.html'), () => {
                            // Register service worker if supported.
                            if ('serviceWorker' in navigator) {
                                navigator.serviceWorker.register('service-worker.js', {
                                    scope: '/distribution.pl/'
                                });
                            }
                            this._notifyNetworkStatus();
                            this.loadComplete = true;
                        });
                    });
                }
            }

            _notifyNetworkStatus() {
                let oldOffline = this.offline;
                this.offline = !navigator.onLine;
                // Show the snackbar if the user is offline when starting a new session
                // or if the network status changed.
                if (this.offline || (!this.offline && oldOffline === true)) {
                    if (!this._networkSnackbar) {
                        this._networkSnackbar = document.createElement('shop-snackbar');
                        this.root.appendChild(this._networkSnackbar);
                    }
                    this._networkSnackbar.innerHTML = this.offline ?
                        'You are offline' : 'You are online';
                    this._networkSnackbar.open();
                }
            }

            _toggleDrawer() {
                this.drawerOpened = !this.drawerOpened;
            }

            // Elements in the app can notify section changes.
            // Response by a11y announcing the section and syncronizing the category.
            _onChangeSection(event) {
                let detail = event.detail;

                // Scroll to the top of the page when navigating to a non-list page. For list view,
                // scroll to the last saved position only if the category has not changed.
                let scrollTop = 0;
                if (this.page === 'list') {
                    if (this.categoryName === detail.category) {
                        scrollTop = this._listScrollTop;
                    } else {
                        // Reset the list view scrollTop if the category changed.
                        this._listScrollTop = 0;
                    }
                }
                // Use `Polymer.AppLayout.scroll` with `behavior: 'silent'` to disable header scroll
                // effects during the scroll.
                Polymer.AppLayout.scroll({
                    top: scrollTop,
                    behavior: 'silent'
                });

                this.categoryName = detail.category || '';

                // Announce the page's title
                if (detail.title) {
                    //document.title = detail.title + ' - '+this.appInfo.result.app_name;
                    this._announce(detail.title + ', loaded');
                }
            }

            // Elements in the app can notify a change to be a11y announced.
            _onAnnounce(e) {
                this._announce(e.detail);
            }

            // A11y announce the given message.
            _announce(message) {
                this._a11yLabel = '';
                this._announceDebouncer = Polymer.Debouncer.debounce(this._announceDebouncer,
                    Polymer.Async.timeOut.after(100), () => {
                        this._a11yLabel = message;
                    });
            }

            // This is for performance logging only.
            _domChange(e) {
                if (window.performance && performance.mark && !this.__loggedDomChange) {
                    let target = e.composedPath()[0];
                    let host = target.getRootNode().host;
                    if (host && host.localName.match(this.page)) {
                        this.__loggedDomChange = true;
                        performance.mark(host.localName + '.domChange');
                    }
                }
            }

            _onFallbackSelectionTriggered() {
                this.page = '404';
            }

            _computeShouldShowTabs(page, smallScreen) {
                return (page === 'home' || page === 'list' || page === 'detail') && !smallScreen;
            }

            _computeShouldRenderTabs(_shouldShowTabs, loadComplete) {
                return _shouldShowTabs && loadComplete;
            }

            _computeShouldRenderDrawer(smallScreen, loadComplete) {
                return smallScreen && loadComplete;
            }

            _computePluralizedQuantity(quantity) {
                return quantity + ' ' + (quantity === 1 ? 'item' : 'items');
            }
            navToPage(value) {
                let url = null;
                if (typeof(value) == "string") {
                    url = value;
                } else {
                    url = value.currentTarget.href;
                    if (!url) {
                        url = value.currentTarget.getAttribute("href");
                    }
                }
                let path = null;
                let params = new Object();
                if (url.indexOf("?") != -1) {
                    path = url.split("?")[0];
                    let query = url.split("?")[1];
                    query = query.split("&amp;").join("&");
                    let queryParams = query.split("&");
                    for (let i = 0; i < queryParams.length; i++) {
                        let queryParam = queryParams[i];
                        if (queryParam.indexOf("=") != -1) {
                            params[queryParam.substring(0, queryParam.indexOf("="))] = queryParam.substring(queryParam.indexOf("=") + 1, queryParam.length);
                        } else {
                            params[queryParam] = "";
                        }
                    }
                } else {
                    path = url;
                }
                app.queryParams = params;
                app.route = {
                    path: path,
                    prefix: ""
                };

            }
            _openLoading() {
                this.loadingCount++;
                this.$.loading.active = true;
            }
            _closeLoading() {
                this.loadingCount--;
                if (this.loadingCount == 0) {
                    this.$.loading.active = false;
                }
            }
        }

        customElements.define(ShopApp.is, ShopApp);

    </script>

</dom-module>
